package com.csii.mytest.database;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.Nullable;

/**
 * Created by 顾博君 on 2017/3/1.
 */

public class MyContentProvider extends ContentProvider {
    private MySQLiteHelper mySQLiteHelper = null;
    private static final String authority = "com.csii.mytest.database.MyContentProvider";
    //匹配Uri
    //常量UriMatcher.NO_MATCH表示不匹配任何路径的返回码(-1)。
    private static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);

    private static final int STUDENT = 1;
    private static final int STUDENTS = 2;

    static {
        URI_MATCHER.addURI(authority, MySQLiteHelper.TABLEC_NAME, STUDENTS);
        URI_MATCHER.addURI(authority, MySQLiteHelper.TABLEC_NAME + "/#", STUDENT);
    }

    @Override
    public boolean onCreate() {
        mySQLiteHelper = new MySQLiteHelper(getContext());
        return false;
    }

    @Nullable
    @Override
    public Cursor query(Uri uri, String[] strings, String s, String[] strings1, String s1) {
        //数据库操作实例
        SQLiteDatabase sqLiteDatabase = mySQLiteHelper.getReadableDatabase();
        //数据库插入
        Cursor cursor = sqLiteDatabase.query(MySQLiteHelper.TABLEC_NAME,
                null, null, null, null, null, null);
        return cursor;
    }

    @Nullable
    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Nullable
    @Override
    public Uri insert(Uri uri, ContentValues contentValues) {
        Uri resultUri = null;
        int flag = URI_MATCHER.match(uri);
        switch (flag) {
            case STUDENTS:
                //数据库操作实例
                SQLiteDatabase sqLiteDatabase = mySQLiteHelper.getWritableDatabase();
                //数据库插入
                long id = sqLiteDatabase.insert(MySQLiteHelper.TABLEC_NAME, null, contentValues);
                resultUri = ContentUris.withAppendedId(uri, id);
                break;
        }
        return resultUri;
    }

    @Override
    public int delete(Uri uri, String s, String[] strings) {
        return 0;
    }

    @Override
    public int update(Uri uri, ContentValues contentValues, String s, String[] strings) {
        return 0;
    }
}
